// pages/city/city.js
const {http} = require("../../module/http")
const app = getApp();
Page({
  data: {
    keyword:"",
    result:"",
    searchCities:"",
    visitedCities:"",
    location:""
  },
  onLoad(){
    var location = wx.getStorageSync('locationCity');
    if(location){
      this.setData({
        location
      })
    }

    var cities = wx.getStorageSync('cities');
    if(cities){
      this.setData({
        visitedCities:cities
      })
    }else{
      wx.setStorageSync('cities', []);
    }

    http({
      url:":8000/city"
    }).then(res=>{
      console.log(res);
      let result = res.data.data;
      let lists = Object.keys(result.cities)
      this.setData({
        result,
        lists
      })
    })
  },

  handleClick(event){
    var cities = wx.getStorageSync('cities')
    var name = event.currentTarget.dataset.name;
    if(!cities.includes(name)){
      cities.unshift(name)
    }
    wx.setStorageSync('cities', cities.slice(0,3))

    app.globalData.currentCity = name;
    wx.navigateBack();
  },
  handleChange(event){
    var keyword = event.detail;
    var searchCities = this.filterCity(keyword)
    console.log(searchCities)
    this.setData({
      keyword,
      searchCities
    })
  },

  filterCity(keyword){
    var cities = this.data.result.cities;
    var arr =[];
    for(let key in cities){
      cities[key].forEach(item=>{
        if(item.name.includes(keyword) || item.spell.includes(keyword)){
          arr.push(item)
        }
      })
    }
    return arr
  }
})